/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package sessionbean;

import entitybean.Musicians;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 *
 * @author Thien Nguyen
 */
@Stateless
@org.jboss.ejb3.annotation.RemoteBinding(jndiBinding="MusiciansJNDI")
@org.jboss.ejb3.annotation.LocalBinding(jndiBinding = "MusiciansLocalJNDI")
public class MusiciansSessionBean implements MusiciansSessionBeanRemote, MusiciansSessionBeanLocal {
    @PersistenceContext(unitName = "J2EE_ShareMusic-ejbPU")
    private EntityManager em;

    public void persist(Object object) {
        em.persist(object);
    }

    public List loadMusician() {
        String jpql = "SELECT a FROM Musicians a";
        javax.persistence.Query query = em.createQuery(jpql);
        List list = query.getResultList();
        return list;
    }

    public List getMusician(int id) {
        String jpql = "SELECT a FROM Musicians a WHERE a.musicianID =:id";
        javax.persistence.Query query = em.createQuery(jpql);
        query.setParameter("id", id);
        List list = query.getResultList();
        return list;
    }

    public boolean deleteMusician(int id) {
        String jpql = "UPDATE Songs a SET a.musicians.musicianID =:param WHERE a.musicians.musicianID =:id";
        javax.persistence.Query query = em.createQuery(jpql);
        query.setParameter("param", null);
        query.setParameter("id", id);
        int result = query.executeUpdate();
        Musicians musician = em.find(Musicians.class, id);
        if(musician != null) {
            em.remove(musician);
            return true;
        }
        else return false;
    }

    public boolean addMusician(String name) {
        String jpql = "SELECT a FROM Musicians a WHERE a.musicianName =:name";
        javax.persistence.Query query = em.createQuery(jpql);
        query.setParameter("name", name);
        List list = query.getResultList();
        if (list.size() == 0) {
            Musicians newA = new Musicians(name);
            persist(newA);
            return true;
        } else {
            return false;
        }
    }


}
